<template>
    <el-dialog 
    :visible.sync="visible" 
    title="部门详情"
    width="500px"
    @close="handleClose">
        <el-form ref="ruleForm" :rules="rules" :model="formData" label-width="100px"  class="demo-ruleForm">
            <el-form-item label="部门名称" prop="dname">
                <el-input v-model="formData.dname"></el-input>
            </el-form-item>
        
            <el-form-item>
                <el-button type="primary" @click="handleSubmit">提交</el-button>
                <el-button @click="handleClose">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script>
export default {
    name: 'deptInfo',
    props: {
        visible: Boolean,
        deptData: Object,
    },
    data() {
        return {
            formData: {
                deptno: null,
                dname: ''
            },
            rules: {
                dname: [{ required: true, message: '请输入部门名称', trigger: 'blur' }]
            }
        }
    },
    watch: {
        deptData: {
            handler(newVal) {
                if (newVal) {
                    this.loadFormData()
                }
            }
        }
    },
    methods: {
        loadFormData() {
            this.formData = this.deptData
        },

        handleSubmit(){
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    if(this.formData.deptno == null){
                        this.formData.deptno = 0
                        this.$http.post('/addDept', this.formData).then(res => {
                            if(res.data == 'success') {
                                this.$message.success('添加成功')
                                this.handleClose()
                            } else {
                                this.$message.error('添加失败')
                            }
                        }).catch(() => {
                            this.$message.warning('系统异常')
                        })
                    } else {
                        this.$http.post('/editDept', this.formData).then(res => {
                            if(res.data == 'success') {
                                this.$message.success('更新成功')
                                this.handleClose()
                            } else {
                                this.$message.error('更新失败')
                            }
                        }).catch(() => {
                            this.$message.warning('系统异常')
                        })
                    }
                } else {
                    return false;
                }
            })
        },

        handleClose() {
            this.$refs['ruleForm'].resetFields()
            this.$emit('close')
        }
    }
}
</script>

<style>

</style>